package org.jeecg.modules.login.api;


import lombok.Data;
import lombok.SneakyThrows;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.login.LoginService;
import org.jeecg.config.thirdapp.ThirdAppConfig;
import org.jeecg.modules.login.handler.wechat.WechatMiniProgramHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * [微信小程序] 免密登录
 *
 * @author tianyi.jiang
 * @since 1.2.2
 */
@RestController
@RequestMapping("/sys/wechat/mp")
@ConditionalOnExpression("'${basicplatform.login.wechat-mini-program.enable:false}'.equals('true')")
public class WeChatMiniProgramLogin {

    private final WechatMiniProgramHandler wechatMiniProgramHandler;

    private final LoginService loginService;

    @SneakyThrows
    @GetMapping("/login/{jsCode}")
    public Result<?> preLogin(@PathVariable String jsCode) {
        String openId = wechatMiniProgramHandler.getOpenId(jsCode);
        return loginService.auth4WechatMiniProgram(openId, ThirdAppConfig.WECHAT_MINI_PROGRAM);
    }

    @SneakyThrows
    @PostMapping("/auth")
    public Result<?> register(@RequestBody WeChatMiniProgramParameter weChatMiniProgramParameter) {
        // 获取授权用户手机号码
        String phone = wechatMiniProgramHandler.getPhone(weChatMiniProgramParameter.getCode());
        return loginService.register4WechatMiniProgram(weChatMiniProgramParameter.getOpenId(), phone);
    }

    public WeChatMiniProgramLogin(WechatMiniProgramHandler wechatMiniProgramHandler, LoginService loginService) {
        this.wechatMiniProgramHandler = wechatMiniProgramHandler;
        this.loginService = loginService;
    }

    @Data
    public static class WeChatMiniProgramParameter implements Serializable {

        private static final long serialVersionUID = 1L;
        /**
         * 微信小程序授权唯一标识
         */
        private String openId;
        /**
         * 电话号码授权码
         */
        private String code;

    }
}